package com.example.tool.activtiy;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.tool.R;
import com.example.tool.activtiy.base.BaseActivity;
import com.example.tool.adapter.DictSelectAdapter;
import com.example.tool.adapter.FavorMovieAdapter;
import com.example.tool.adapter.HealthMemberAdapter;
import com.example.tool.bean.CommonBean;
import com.example.tool.bean.SelectBean;
import com.example.tool.bean.UserEntity;
import com.example.tool.listener.OnItemListener;
import com.example.tool.mvp.CommonPresent;
import com.example.tool.util.CreateIDCardNo;
import com.example.tool.util.DataRequest;
import com.example.tool.util.DebugLog;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.othershe.nicedialog.BaseNiceDialog;
import com.othershe.nicedialog.NiceDialog;
import com.othershe.nicedialog.ViewConvertListener;
import com.othershe.nicedialog.ViewHolder;

import java.util.List;

import butterknife.BindView;

import static com.example.tool.util.DebugLog.ANIMATION;

/**
 * Created Date 2019/8/30
 *
 * @author liangkun
 * description：流式布局
 */
public class FlexboxLayoutActivity extends BaseActivity<CommonPresent> {
    @BindView(R.id.rv_layout)
    protected RecyclerView mRvFavor;
    @BindView(R.id.cardview_dialog)
    protected CardView cardViewDialog;

    @BindView(R.id.rv_layout_hl)
    protected RecyclerView memberList;
    @BindView(R.id.indicator_lay)
    protected RadioGroup indicatorLay;

    @BindView(R.id.tv_title)
    protected TextView tvTitle;
    private FavorMovieAdapter mAdapter;
    private HealthMemberAdapter memberManagementAdapter;
    private int currentIndicatorIndex;
    private PagerSnapHelper snapHelper;
    private List<UserEntity> userEntities;

    @Override
    protected int getLayoutId() {
        return R.layout.flexbox_layout_activity;
    }

    @Override
    protected void initView() {
        tvTitle.setText("流式布局");
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void initData() {
        List<SelectBean> beanList = DataRequest.getBeanList();
        mAdapter = new FavorMovieAdapter(R.layout.flex_item_btn, beanList, mContext);
        FlexboxLayoutManager manager = new FlexboxLayoutManager(this);
        //设置主轴排列方式
        manager.setFlexDirection(FlexDirection.ROW);
        //设置是否换行
        manager.setFlexWrap(FlexWrap.WRAP);
//        mRvFavor.setItemAnimator(new DefaultItemAnimator());
        manager.setAlignItems(AlignItems.STRETCH);
        manager.setJustifyContent(JustifyContent.FLEX_START);
        mRvFavor.setLayoutManager(manager);
        mRvFavor.setAdapter(mAdapter);
        initMemberList();
        userEntities = DataRequest.getPersonList();
        initMemberData(userEntities);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @SuppressLint("ResourceType")
    private void initMemberData(List<UserEntity> userEntities) {

        if (userEntities.size() < 6) {
            //家庭成员最多6人
            userEntities.add(userEntities.size(), new UserEntity());
        }
        memberManagementAdapter.setNewData(userEntities);
        initIndicator(userEntities.size());
        indicatorLay.check(0);
        memberList.smoothScrollToPosition(0);
    }

    private void initMemberList() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
        memberList.setLayoutManager(linearLayoutManager);
        memberManagementAdapter = new HealthMemberAdapter();
        memberList.setAdapter(memberManagementAdapter);
        snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(memberList);
        memberList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //mScrolled为true表示之前进行过滚动.
                //newState为SCROLL_STATE_IDLE状态表示滚动结束停下来
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    View snapView = snapHelper.findSnapView(linearLayoutManager);
                    int position = recyclerView.getChildAdapterPosition(snapView);
                    DebugLog.d(ANIMATION + " newState " + newState + " childAdapterPosition " + position);
                    indicatorLay.check(position);

                }

            }

        });

        memberManagementAdapter.setOnAddClickLister(new OnItemListener() {
            @Override
            public void OnItemClick(int postion) {
                startActivityForResult(new Intent(FlexboxLayoutActivity.this, CallBackActivity.class), 10056);
            }
        });
    }

    void snapToTargetExistingView() {
        if (memberList == null) {
            return;
        }
        RecyclerView.LayoutManager layoutManager = memberList.getLayoutManager();
        if (layoutManager == null) {
            return;
        }
        //找出SnapView
        View snapView = snapHelper.findSnapView(layoutManager);
        if (snapView == null) {
            return;
        }
        //计算出SnapView需要滚动的距离
        int[] snapDistance = snapHelper.calculateDistanceToFinalSnap(layoutManager, snapView);
        //如果需要滚动的距离不是为0，就调用smoothScrollBy（）使RecyclerView滚动相应的距离
        if (snapDistance != null && snapDistance.length > 0) {
            if (snapDistance[0] != 0 || snapDistance[1] != 0) {
                memberList.smoothScrollBy(snapDistance[0], snapDistance[1]);
            }
        }

    }


    private void initIndicator(int size) {
        indicatorLay.removeAllViews();
        for (int i = 0; i < size; i++) {
            RadioButton radioButton = new RadioButton(this);
            radioButton.setId(i);
            LinearLayout.LayoutParams layoutParams
                    = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(5, 0, 5, 0);
            radioButton.setLayoutParams(layoutParams);
            radioButton.setButtonDrawable(null);
            radioButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.line_indicator, 0, 0, 0);
            indicatorLay.addView(radioButton);
        }
    }

    @Override
    protected void initEvent() {
        cardViewDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDictSelect(FlexboxLayoutActivity.this, getSupportFragmentManager(), DataRequest.getCommonBeanList());
            }
        });

    }

    /**
     * @description 显示字典数据
     * @author liangkun
     * @time 2020/7/14 17:36
     */
    public static void showDictSelect(Context context, FragmentManager manager, List<CommonBean> commonBeans) {
        NiceDialog niceDialog = NiceDialog.init()
                .setLayoutId(R.layout.common_dialog_select)
                .setConvertListener(new ViewConvertListener() {

                    private DictSelectAdapter adapter;

                    @Override
                    protected void convertView(ViewHolder viewHolder, final BaseNiceDialog baseNiceDialog) {
                        RecyclerView recyclerView = viewHolder.getView(R.id.recyclerView);
                        recyclerView.addItemDecoration(
                                new DividerItemDecoration(context,
                                        DividerItemDecoration.VERTICAL));
                        adapter = new DictSelectAdapter(commonBeans);
                        recyclerView.setAdapter(adapter);

                    }
                });

        if (commonBeans.size() > 5) {
            niceDialog.setShowBottom(true)
                    .setMargin(16)
                    .setHeight(250)
                    .show(manager);
        } else {
            niceDialog.setShowBottom(true)
                    .setMargin(16)
                    .show(manager);
        }
    }

    @Override
    protected CommonPresent createPresenter() {
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10056 && resultCode == RESULT_OK) {
            UserEntity selectBean = new UserEntity();
            selectBean.setSex(1);
            selectBean.setName("两捆mn");
            selectBean.setCertificate(new CreateIDCardNo().getRandomID());
            selectBean.setRelationship("兄弟");
            selectBean.setPhone("13713581387");
            userEntities.add(userEntities.size() - 1, selectBean);
            initMemberData(userEntities);
        }
    }
}
